package net.zjitc.android2019.ch3storage;

import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import net.zjitc.android2019.R;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Ch3FileOuterActivity extends AppCompatActivity {
    Button btn1,btn2;
    TextView tv;
    String fileName="hello2.txt";

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ch3_file_outer);
        /* 关联控件*/
        btn1=findViewById(R.id.ch3_file_outer_btn_write);
        btn2=findViewById(R.id.ch3_file_outer_btn_read);
        tv=findViewById(R.id.ch3_file_outer_tv);

        /* 动态申请权限:放在OnCreate方法*/
        String[] p={"android.permission.WRITE_EXTERNAL_STORAGE","android.permission.READ_EXTERNAL_STORAGE"};
        ActivityCompat.requestPermissions(Ch3FileOuterActivity.this,p,1);

        /* 按钮点击事件及绑定*/
        View.OnClickListener listener=new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.ch3_file_outer_btn_write:
                        write();
                        break;
                    case R.id.ch3_file_outer_btn_read:
                        read();
                        break;
                }
            }
        };
        btn1.setOnClickListener(listener);
        btn2.setOnClickListener(listener);
    }

    /**
     * *   判断外部设备是否可用
     *         *     若可用：
     *         *    1）获取SD卡路径
     *         *    2）生成File对象
     *         *    3）利用Java流将内容写入文件
     *         *       FileInputStream的构造方法有传入File参数
     *         *       将其转换为BufferedReader
     *         *
     */
    private void read() {
        String device=Environment.getExternalStorageState();
        if(device.equals(Environment.MEDIA_MOUNTED)){
            File path=Environment.getExternalStorageDirectory();
            File file=new File(path,"h2.txt");
            FileInputStream in=null;
            BufferedReader br=null;
            try {
                in=new FileInputStream(file);
                br=new BufferedReader(new InputStreamReader(in));
                String line=null;
                String s="";
                while ((line=br.readLine())!=null){
                   s+=line+"\n" ;
                }
                tv.setText(s);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 1、动态申请权限
     * 2、判断外部设备是否可用
     *           若可用：
     *           1）获取SD卡路径
     *           2）生成File对象
     *           3）利用Java流将内容写入文件
     *             FileOutputStream的构造方法有传入File参数
     *             将其转换为BufferedWriter
     *  模拟器6.0 文件路径在storage/emulated/0/..
     *  7.0以上该目录不可用，还需要额外的代码，路径是在storage/self/primary/...
     */
    private void write() {
        String message="Android\nIOS";
        /* 获取外部设备的状态*/
        String device=Environment.getExternalStorageState();
        /* MEDIA_MOUNTED 存储媒体已经挂载，并且挂载点可读/写*/
        if(device.equals(Environment.MEDIA_MOUNTED)) {
            /*获取外部存储设备的路径 */
           File path=Environment.getExternalStorageDirectory();
           /* file 存储的文件 */
           File file=new File(path,"h2.txt");
           /* 通过IO流的方式将 message中的内容 写入到file文件 */
           FileOutputStream out=null;
           BufferedWriter bw=null;
            try {
                out=new FileOutputStream(file);
                bw=new BufferedWriter(new OutputStreamWriter(out));
                bw.write(message);
                bw.flush();
                Toast.makeText(this, "写入成功", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                /*关闭流*/
            }
        }
    }
}
